package com.wuzuqing.android.eightdiagrams

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.CheckBox
import android.widget.EditText
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import com.wuzuqing.android.eightdiagrams.base.BaseAdapter
import com.wuzuqing.android.eightdiagrams.dao.BaZhiHistory
import com.wuzuqing.android.eightdiagrams.db.DbManager
import com.wuzuqing.android.eightdiagrams.model.*
import com.wuzuqing.android.eightdiagrams.term.ExactDate
import com.wuzuqing.android.eightdiagrams.term.Solar
import com.wuzuqing.android.eightdiagrams.utils.*
import java.text.SimpleDateFormat
import java.util.*

class BaZiActivity : BaseActivity() {
    lateinit var mTvTime: TextView
    lateinit var mTvCity: TextView
    lateinit var mTvResult: TextView
    lateinit var mTvExtra: TextView
    lateinit var vRcvResult: RecyclerView
    lateinit var vRcvDaYun: RecyclerView
    lateinit var vRcvLiuNian: RecyclerView
    lateinit var vRcvLiuYue: RecyclerView
    lateinit var vRcvLiuRi: RecyclerView
    var selectTime = 0L
    var mSelectCity: City? = null
    var mSelectProvince = ""
    lateinit var cityContainer: View
    lateinit var operBar: View
    lateinit var cityRcv: RecyclerView
    lateinit var provinceRcv: RecyclerView
    lateinit var mSexContainer: RadioGroup
    lateinit var mEtName: EditText
    lateinit var mRbSum: CheckBox
    var mHistoryData: BaZhiHistory? = null
    private var dayMin = 86400 * 1000

    @SuppressLint("SimpleDateFormat")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_bazi)
        mTvTime = findViewById(R.id.tv_time)
        mTvCity = findViewById(R.id.tv_city)
        mTvResult = findViewById(R.id.tv_result)
        mTvExtra = findViewById(R.id.tv_extra)
        cityContainer = findViewById(R.id.cityContainer)
        operBar = findViewById(R.id.operBar)
        provinceRcv = findViewById(R.id.provinceRcv)
        cityRcv = findViewById(R.id.cityRcv)
        mSexContainer = findViewById(R.id.sex_container)
        vRcvResult = findViewById(R.id.rcv_result)
        vRcvDaYun = findViewById(R.id.rcv_dayun)
        vRcvLiuNian = findViewById(R.id.rcv_liunian)
        vRcvLiuYue = findViewById(R.id.rcv_liuyue)
        vRcvLiuRi = findViewById(R.id.rcv_liuri)
        mRbSum = findViewById(R.id.cb_sum)
        mEtName = findViewById(R.id.et_name)
        initRcv()
        initResultRcv()
        initDaYunLiuRcv()
        val ca = Calendar.getInstance()
        intent?.getSerializableExtra("data")?.also {
            mHistoryData = it as BaZhiHistory
            mHistoryData?.let { history ->
                ca.timeInMillis = history.createTime
                mRbSum.isChecked = history.useSumTime == 1
                if (history.sexType != 1) {
                    findViewById<RadioButton>(R.id.sex_girl).isChecked = true
                }
                mEtName.text.clear()
                mEtName.text.append(history.nickName)
            }
        } ?: also {
            ca.set(2002, 5, 15, 0, 1, 0)
        }

        findViewById<View>(R.id.selectTime).setOnClickListener {
            CardDatePickerDialog.builder(this)
                .setChooseDateModel(DateTimeConfig.DATE_LUNAR)
                .setDefaultTime(selectTime)
                .setOnChoose { time ->
                    chooseTime(time)
                }
                .build().show()
        }
        findViewById<View>(R.id.preDay).setOnClickListener {
            optTime(Calendar.DATE, -1)
        }
        findViewById<View>(R.id.menuBtn).setOnClickListener {
            if (operBar.isShown){
                operBar.visibility = View.GONE
            }else{
                operBar.visibility = View.VISIBLE
            }
            startCs()
        }
        findViewById<View>(R.id.nextDay).setOnClickListener {
            optTime(Calendar.DATE, 1)
        }
        findViewById<View>(R.id.nextMonth).setOnClickListener {
            optTime(Calendar.MONTH, 1)
        }
        findViewById<View>(R.id.preMonth).setOnClickListener {
            optTime(Calendar.MONTH, -1)
        }
        findViewById<View>(R.id.preYear).setOnClickListener {
            optTime(Calendar.YEAR, -1)
        }
        findViewById<View>(R.id.nextYear).setOnClickListener {
            optTime(Calendar.YEAR, 1)
        }
        findViewById<View>(R.id.saveHistory).setOnClickListener {
            val name = mEtName.text.toString()
            if (name.isEmpty()) {
                Toast.makeText(it.context, "请输入姓名", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            DbManager.getInstance().db.baZhiHistoryDao().insertUser(
                BaZhiHistory(
                    selectTime, System.currentTimeMillis(),
                    name, mSelectCity?.toString().orEmpty(),
                    if (mRbSum.isChecked) 1 else 0,
                    if (mSexContainer.checkedRadioButtonId == R.id.sex_boy) 1 else 0
                )
            )
        }
        findViewById<View>(R.id.selectCity).setOnClickListener {
            if (cityContainer.isShown) {
                cityContainer.visibility = View.GONE
                return@setOnClickListener
            }
            cityContainer.bringToFront()
            cityContainer.visibility = View.VISIBLE
        }
        findViewById<View>(R.id.start).setOnClickListener {
            startCs()
        }
        chooseTime(ca.timeInMillis)
    }

    private fun optTime(field: Int, value: Int) {
        val instance = Calendar.getInstance()
        instance.timeInMillis = selectTime
        instance.add(field, value)
        chooseTime(instance.timeInMillis)
    }

    private fun initDaYunLiuRcv() {
        vRcvDaYun.layoutManager = GridLayoutManager(this, 10)
        vRcvDaYun.adapter = TextItemAdapter().also {
            it.setOnItemClickListener(object : BaseAdapter.OnItemClickListener<ITextItem> {
                override fun onItemClick(data: ITextItem, position: Int) {
                    try {
                        selectDaYun(position)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    reBuild()
                }
            })
        }

        vRcvLiuNian.layoutManager = GridLayoutManager(this, 10)
        vRcvLiuNian.adapter = TextItemAdapter().also {
            it.setOnItemClickListener(object : BaseAdapter.OnItemClickListener<ITextItem> {
                override fun onItemClick(data: ITextItem, position: Int) {
                    selectLiuNian(position)
                    reBuild()
                }
            })
        }

        vRcvLiuYue.layoutManager = GridLayoutManager(this, 12)
        vRcvLiuYue.adapter = TextItemAdapter().also {
            it.setOnItemClickListener(object : BaseAdapter.OnItemClickListener<ITextItem> {
                override fun onItemClick(data: ITextItem, position: Int) {
                    selectLiuYue(position)
                    reBuild()
                }
            })
        }

        vRcvLiuRi.layoutManager = GridLayoutManager(this, 10)
        vRcvLiuRi.adapter = TextItemAdapter().also {
            it.setOnItemClickListener(object : BaseAdapter.OnItemClickListener<ITextItem> {
                override fun onItemClick(data: ITextItem, position: Int) {
                    selectLiuRi(position)
                    reBuild()
                }
            })
        }
    }

    private var info: BaZiInfo? = null
    private var currentYear = 0
    private var currentMonth = 0
    private var currentDay = 0
    private fun startCs() {

        val my = LuozhuangSunTime()
        val fixTime = my.calculateTime(selectTime, mSelectCity?.toString().orEmpty())
        LogUtils.d("calculateTime:fixTime:$${fixTime},selectTime:$selectTime")

        val calendar = Calendar.getInstance()
        val today = Solar.fromDate(ExactDate.fromCal(calendar))
        today.lunar?.also {
            currentYear = it.year
            currentMonth = it.month
            currentDay = it.day
        }
        calendar.timeInMillis = if (mRbSum.isChecked) fixTime.getRealTime() else fixTime.time

        val solar = Solar.fromDate(ExactDate.fromCal(calendar))
//        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm")

//        val birth = Birth(calendar)
//        birth.horoscope(sdf.format(calendar.time))
        val info = BaZhiHelper.buildBaZhiInfo1(
            fixTime.getRealTime(), solar, mSexContainer.checkedRadioButtonId == R.id.sex_boy
        ).also {
            this.info = it
        }
        info.time = fixTime.time
        info.sumTime = fixTime.sumTime
        reBuild()
        var currentIndex = 0
        (vRcvDaYun.adapter as TextItemAdapter).setList(info.buildDaYunList().also {
            it.forEachIndexed { index, iTextItem ->
                (iTextItem as DaYunItem).also { item ->
                    if (item.year <= currentYear && (item.year + 10) > currentYear) {
                        currentIndex = index
                        (vRcvDaYun.adapter as TextItemAdapter).performClickItem(index)
                    }
                }
            }
        })
        info.daYunIndex = -1
        info.liuNianIndex = -1
        selectDaYun(currentIndex)
        mTvResult.text = info.buildTitle()
        reBuild()
    }


    fun selectDaYun(pos: Int) {
        if (pos == info!!.daYunIndex) {
            return
        }
        info?.daYunIndex = pos
        (vRcvDaYun.adapter as TextItemAdapter).getItem(pos)?.also {
            info?.apply {
                BaZhiHelper.setDyInfo(this,it.ganZhi)
            }
        }
        var currentIndex = 0
        (vRcvLiuNian.adapter as TextItemAdapter).setList((info?.getLiuNian(pos) ?: mutableListOf()).also {
            it.onEachIndexed { index, iTextItem ->
                (iTextItem as LiuNianItem).also { item ->
                    if (item.year == currentYear) {
                        currentIndex = index
                        (vRcvLiuNian.adapter as TextItemAdapter).performClickItem(index)
                    }
                }
            }
        })
        info?.liuNianIndex = -1
        selectLiuNian(currentIndex)
    }

    private fun selectLiuNian(pos: Int) {
        if (pos == info!!.liuNianIndex) {
            return
        }
        info?.liuNianIndex = pos
        var currentIndex = 0
        (vRcvLiuYue.adapter as TextItemAdapter).setList(
            (info?.getLiuYue() ?: mutableListOf()).also {
                it.onEachIndexed { index, iTextItem ->
                    (iTextItem as LiuYueItem).also { item ->
                        LogUtils.d("selectLiuNian"+item.month+","+currentMonth)
                        if (item.year == currentYear && item.month == currentMonth) {
                            currentIndex = index
                            (vRcvLiuYue.adapter as TextItemAdapter).performClickItem(index)
                        }
                    }
                }
            })
        (vRcvLiuNian.adapter as TextItemAdapter).getItem(pos)?.also {
            info?.apply {
                BaZhiHelper.setLnInfo(this,it.ganZhi)
            }
        }
        info?.liuYueIndex = -1
        selectLiuYue(currentIndex)
    }

    private fun selectLiuYue(pos: Int) {
        if (pos == info!!.liuYueIndex) {
            return
        }
        info?.liuYueIndex = pos
        info?.liuRiIndex = -1
        var currentIndex = 0
        (vRcvLiuRi.adapter as TextItemAdapter).setList(
            (info?.getLiuRi() ?: mutableListOf()).also {
                it.onEachIndexed { index, iTextItem ->
                    (iTextItem as LiuRIItem).also { item ->
                        if (item.lunarYear == currentYear && item.lunarMonth == currentMonth && item.lunarDay == currentDay) {
                            currentIndex = index
                            (vRcvLiuRi.adapter as TextItemAdapter).performClickItem(index)
                        }
                    }
                }
            }
        )
        (vRcvLiuYue.adapter as TextItemAdapter).getItem(pos)?.also {
            info?.apply {
                BaZhiHelper.setLyInfo(this,it.ganZhi)
            }
        }
        selectLiuRi(currentIndex)
    }

    private fun reBuild() {
        info?.also {
            (vRcvResult.adapter as ResultAdapter).setList(it.buildList())
            mTvExtra.text = it.buildBottom(false)
        }
    }
    fun selectLiuRi(pos: Int) {
        if (pos == info!!.liuRiIndex) {
            return
        }
        info!!.liuRiIndex = pos
        (vRcvLiuRi.adapter as TextItemAdapter).getItem(pos)?.also {
            info?.apply {
                BaZhiHelper.setLrInfo(this,it.ganZhi)
            }
        }
    }

    private fun chooseTime(time: Long) {
        selectTime = time
        mTvTime.text = "选择日期" + SimpleDateFormat("yyyy-MM-dd HH:mm").format(time)
        startCs()
    }

    private fun initResultRcv() {
        vRcvResult.layoutManager = GridLayoutManager(this, 9)
        vRcvResult.adapter = ResultAdapter()
    }


    private fun initRcv() {
        provinceRcv.layoutManager = LinearLayoutManager(this)
        val provinceNames = DataUtils.getProvinceNames()
        provinceRcv.adapter = ProvinceAdapter().apply {
            setList(provinceNames)
            setOnItemClickListener(object : BaseAdapter.OnItemClickListener<String> {
                override fun onItemClick(data: String, position: Int) {
                    onSelectProvince(data);
                }
            })
        }
        cityRcv.layoutManager = LinearLayoutManager(this)
        cityRcv.adapter = CityAdapter().apply {
            setOnItemClickListener(object : BaseAdapter.OnItemClickListener<City> {
                override fun onItemClick(data: City, position: Int) {
                    mSelectCity = data
                    mTvCity.text = data.toString()
                    cityContainer.visibility = View.GONE
                }
            })
        }

        onSelectProvince("广西")
    }


    fun onSelectProvince(province: String) {
        mSelectProvince = province
        val list = DataUtils.getCity(mSelectProvince)
        var index = 0
        if (province == "广西") {
            index = list.indexOfFirst { it.city == "博白" }
            mTvCity.text = list[index].toString()
        }
        mSelectCity = list[index]
        (cityRcv.adapter as CityAdapter).setList(list)
    }
}
